import { LoginService } from '@service/login.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
	selector: 'app-reset-password',
	templateUrl: './reset-password.component.html',
	styleUrls: ['./reset-password.component.less']
})
export class ResetPasswordComponent extends AbsFormUtil implements OnInit {
	isLoading: boolean;
	constructor(
		private nzModalRef: NzModalRef,
		private fb: FormBuilder,
		private nzMessageService: NzMessageService,
		private loginService: LoginService
	) {
		super();
	}

	ngOnInit(): void {
		this.buildForm();
	}
	buildForm() {
		this.validateForm = this.fb.group({
			oldPsd: [null, [Validators.required]],
			newPsd: [null, [Validators.required]],
			checkPsd: [null, [Validators.required, this.confirmValidator]],
			isShowPassword: [false]
		});
	}
	
	passwordStrengthValidator = (control: FormControl): { [s: string]: boolean } => {
		if (!control.value) {
			return { required: true };
		} else if (!(/^((?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,})$/.test(control.value))) {
			return { strength: true, error: true };
		}
	}
	updateConfirmValidator(): void {
		Promise.resolve().then(() => this.validateForm.controls.checkPsd.updateValueAndValidity());
	}
	confirmValidator = (control: FormControl): { [s: string]: boolean } => {
		if (!control.value) {
			return { required: true };
		} else if (control.value !== this.validateForm.controls.newPsd.value) {
			return { confirm: true, error: true };
		}
	}
	get isShowPassword () {
		return this.getFormControl('isShowPassword').value;
	}
	async handleOk() {
		this.markAsDirty();
		if (this.getFormControl('oldPsd').dirty && this.getFormControl('oldPsd').errors || this.getFormControl('newPsd').dirty && this.getFormControl('newPsd').errors || (this.getFormControl('checkPsd').dirty && this.getFormControl('checkPsd').errors) && (this.getFormControl('checkPsd').hasError('required') || this.getFormControl('checkPsd').hasError('confirm'))) {
			// this.nzMessageServ.warning('密码输入不合法，请修改后再提交！');
			return;
		}
		const params = {
			password: this.getFormControl('oldPsd').value,
			newPassword: this.getFormControl('newPsd').value
		};
		this.isLoading = true;
		const res = await this.loginService.modifyPassword(params);
		this.isLoading = false;
		if (res.code === 500) {
			this.nzMessageService.error(res.msg);
			return;
		}
		this.nzMessageService.success('修改密码成功，请重新登录！');
		this.nzModalRef.triggerOk();
		this.nzModalRef.destroy();
	}
	handleCancel() {
		this.nzModalRef.triggerCancel();
		this.nzModalRef.destroy();
	}

}
